package com.etc.Jdbc;

import java.sql.*;

public class Dome {
    static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
    static String usre = "root";
    static String password = "123456";
    static Connection con = null;
    public static Connection getConnection(){

        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获得数据库的连接
            con = DriverManager.getConnection(url, usre, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
        }

        return con;
    }



    public static void main(String[] args) throws SQLException {

//        select();

//        update();

//        add();

    }


    /**
     * 查询数据库
     */
    public static void select() throws SQLException {

        //3.获得statement对象，操作数据库 返回结果

        String sql = "select * from t_sys";

        //sql 语句的发送器
        PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        //4.处理数据

        while (resultSet.next()) {

            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String ural = resultSet.getString("url");

            System.out.println(id+"\t" + name + "\t" + ural);

        }
        con.close();
    }



    public static void add() throws SQLException {

        String sql = "insert into t_sys(name,url,alexa,country) value (?,?,?,?)";

        Connection connection = DriverManager.getConnection(sql);

        //预编辑
        PreparedStatement p = connection.prepareStatement(sql);
        p.setString(1,"阿里巴巴");
        p.setString(2,"http://alibaba.com");
        p.setInt(3,5);
        p.setString(4,"UN");

        int i = p.executeUpdate();

        System.out.println(i == 1?"添加成功":"添加失败");

    }




    public static void update() throws SQLException {

        String sql = "update  t_sys set name =? where id =? ";



        //预编辑
        PreparedStatement p =getConnection().prepareStatement(sql);
        p.setString(1,"腾讯");
        p.setInt(2,8);

        int i = p.executeUpdate();

        System.out.println( i == 1 ? "更新成功" : "更新失败" );


    }

}
